﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>2013-03-21 16:50:50Z</CreationDate>
</File>
*/
#endregion

using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

namespace Outcoder.Audio
{
	public class SoundEffectAdapter : ISoundEffect
	{
		readonly SoundEffect soundEffect;
		SoundEffectInstance soundEffectInstance;

		public SoundEffectAdapter(Stream audioStream)
		{
			soundEffect = SoundEffect.FromStream(audioStream);
		}

		public SoundEffectAdapter(string filePath)
		{
			Stream stream = TitleContainer.OpenStream(filePath);
			soundEffect = SoundEffect.FromStream(stream);
		}

		public void Play(float volume = 1, float pitch = 0, float pan = 0)
		{
			if (soundEffectInstance == null)
			{
				soundEffectInstance = soundEffect.CreateInstance();
			}
			soundEffectInstance.Play();

			FrameworkDispatcher.Update();
		}

		public void Stop(bool immediate = true)
		{
			if (soundEffectInstance != null)
			{
				soundEffectInstance.Stop(immediate);

				FrameworkDispatcher.Update();
			}
		}

		protected virtual void Dispose(bool disposing)
		{
		    if (disposing)
		    {
		        if (soundEffectInstance != null && !soundEffectInstance.IsDisposed)
		        {
			        soundEffectInstance.Dispose();
		        }

				if (soundEffect != null && !soundEffect.IsDisposed)
				{
					soundEffect.Dispose();
				}
		    }
		}

		public void Dispose()
		{
		    Dispose(true);
		    GC.SuppressFinalize(this);
		}

		~SoundEffectAdapter()
		{
		    Dispose(false);
		}
	}
}
